<template>
    <view class="toptip"
          v-show="visible"
          :class="myClass"
          @click="hide"
          :style="{'opacity':visible?1:0}"
    >{{msg}}
    </view>
</template>

<script>
    export default {
        name: "top-tip",
        data() {
            return {
                visible: false,
                msg: '',
                countDown: undefined,
                closeTime: 0,
                type: 'danger'
            }
        },
        methods: {
            show(msg, type = 'danger', closeTime = 3000) {
                this.type = type;
                this.msg = msg;
                this.visible = true;
                this.closeTime = closeTime;
                if (this.countDown) {
                    clearTimeout(this.countDown);
                    this.countDown = undefined;
                }
                this.countDown = setTimeout(() => {
                  this.hide();
                }, closeTime);
            },
            hide() {
                this.visible = false;
                clearTimeout(this.countDown);
            }
        },
        computed: {
            myClass() {
                const result = [];
                result.push(this.type);
                return result;
            }
        }
    }
</script>

<style scoped lang="less">
    .toptip {
        z-index: 10000;
        -webkit-transition: opacity .3s;
        transition: opacity .3s;
        width: 100%;
        overflow: hidden;
        color: white;
        top: 0;
        left: 0;
        line-height: unit(64, upx);
        font-size: unit(28, upx);
        text-align: center;
        position: fixed;
    }

    .danger, .error {
        background-color: #f6383a;
    }

    .success {
        background-color: #4cd964;
    }

    .warning {
        background-color: #e6a32c;
    }
</style>
